<template>
  <section class="todoapp">
    <!-- 头部部分 -->
      <MytodoListHeader
       @addList="addList"
       ></MytodoListHeader>

    <!-- 主体部分 -->
      <MytodoListBody 
      :list="renderList"
       @changeAll="changeAll"
       @delList="delList"
       @listAll="listAll"
       ></MytodoListBody>

    <!-- 底部部分 -->
      <MytodoListFooter 
      :sum="sum" 
      :showClearBtn="showClearBtn"
      @delAll="delAll"
      :type="type"
      @changeList="changeList"
      ></MytodoListFooter>
  </section>
</template>

<script>
import MytodoListHeader from "./components/MytodoListHeader.vue"
import MytodoListBody from "./components/MytodoListBody.vue"
import MytodoListFooter from "./components/MytodoListFooter.vue"
export default {
  components: {
    MytodoListHeader,
    MytodoListBody,
    MytodoListFooter
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
         {
          id: 1,
          flag: true,
          value: '读万卷书',
        },
        {
          id: 2,
          flag: false,
          value: '行万里路',
        },
      ],
      type: 'all',
    }
  },

  methods: {
    // 绑定选中已完成事件
    changeAll(id, flag) {
      this.list.forEach(item => {
        if(item.id === id) {
          item.flag = flag
        }
      })
    },

    // 绑定添加事件
    addList(value) {
      this.list = [...this.list,{
          id: +new Date(),
          flag: false,
          value,
      }]
    },

    // 删除事件
    delList(id) {
      this.list = this.list.filter(item => item.id !== id)
    },

    // 清除已完成
    delAll() {
      this.list = this.list.filter(item => !item.flag)
    },

    // 切换状态栏
    changeList(value) {
      this.type = value
    },

    // 全选
     listAll(value) {
       this.list.forEach(item => item.flag = value)
     }
  },

  computed: {
    sum() {
      return this.list.filter(item => !item.flag).length
    },

    // 清除已完成
    showClearBtn() {
       return this.list.some(item => item.flag)
    },

    // 渲染页面用动态的list
    renderList() {
     switch (this.type) {
        case "all":
         return this.list
        case "active":
         return this.list.filter(item => !item.flag)
        case "completed":
         return this.list.filter(item => item.flag)
        default:
          return this.list 
      }
    },
  },

  // 监听
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(newVal) {
        localStorage.setItem('list', JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style></style>
